package com.campus.help.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campus.help.common.Result;
import com.campus.help.entity.Labor;
import com.campus.help.mapper.LaborMapper;
import com.campus.help.service.LaborService;
import com.campus.help.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 发布记录控制器
 *
 * @author campus-help
 * @since 2025-09-18
 */
@Slf4j
@RestController
@RequestMapping("/publish-record")
public class PublishRecordController {

    @Autowired
    private LaborService laborService;

    @Autowired
    private LaborMapper laborMapper;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 获取我的发布记录统计
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getPublishStats(HttpServletRequest request) {
        try {
            // 从token中获取用户ID
            String token = getTokenFromRequest(request);
            Long userId = jwtUtils.getStudentIdFromToken(token);

            Map<String, Object> stats = new HashMap<>();
            
            // 获取劳务发布统计
            Page<Labor> laborPage = laborService.getMyPublishedLabors(userId, 1, 1);
            long laborCount = laborPage.getTotal();
            stats.put("laborCount", laborCount);
            stats.put("substituteCount", 0); // 暂时为0
            stats.put("errandCount", 0); // 暂时为0
            stats.put("totalRecords", laborCount); // 总发布数
            
            // 获取已完成的劳务数量
            Page<Labor> completedPage = laborService.getMyPublishedLaborsByStatus(userId, "completed", 1, 1);
            stats.put("completedRecords", completedPage.getTotal());
            
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取发布记录统计失败", e);
            return Result.error("获取发布记录统计失败: " + e.getMessage());
        }
    }

    /**
     * 获取我的发布记录列表
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> getPublishRecords(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String type,
            HttpServletRequest request) {
        try {
            // 从token中获取用户ID
            String token = getTokenFromRequest(request);
            Long userId = jwtUtils.getStudentIdFromToken(token);

            Map<String, Object> result = new HashMap<>();
            java.util.List<Map<String, Object>> allRecords = new java.util.ArrayList<>();
            long totalCount = 0;
            int totalPages = 0;
            
            // 默认显示所有类型，或者根据type参数筛选
            if (type == null || "all".equals(type)) {
                // 获取所有类型的发布记录
                Page<Labor> laborPage = laborService.getMyPublishedLabors(userId, page, size);
                allRecords.addAll(convertLaborToPublishRecords(laborPage.getRecords()));
                totalCount = laborPage.getTotal();
                totalPages = (int) laborPage.getPages();
            } else if ("labor".equals(type)) {
                // 只获取劳务类型
                Page<Labor> laborPage = laborService.getMyPublishedLabors(userId, page, size);
                allRecords.addAll(convertLaborToPublishRecords(laborPage.getRecords()));
                totalCount = laborPage.getTotal();
                totalPages = (int) laborPage.getPages();
            } else {
                // 其他类型暂时返回空
                allRecords = new java.util.ArrayList<>();
                totalCount = 0;
                totalPages = 0;
            }
            
            result.put("records", allRecords);
            result.put("total", totalCount);
            result.put("pages", totalPages);
            result.put("current", page);
            result.put("size", size);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取发布记录列表失败", e);
            return Result.error("获取发布记录列表失败: " + e.getMessage());
        }
    }

    /**
     * 将劳务记录转换为统一的发布记录格式
     */
    private java.util.List<Map<String, Object>> convertLaborToPublishRecords(java.util.List<Labor> labors) {
        java.util.List<Map<String, Object>> records = new java.util.ArrayList<>();
        
        for (Labor labor : labors) {
            Map<String, Object> record = new HashMap<>();
            record.put("id", labor.getId());
            record.put("type", "labor");
            record.put("typeName", "劳务");
            record.put("title", labor.getJobTitle());
            record.put("description", labor.getDescription());
            record.put("status", labor.getStatus());
            record.put("statusName", getStatusName(labor.getStatus()));
            record.put("createTime", formatDateTime(labor.getCreateTime()));
            record.put("location", labor.getLocation());
            record.put("reward", labor.getSalary());
            record.put("viewCount", labor.getViewCount());
            record.put("applyCount", labor.getApplyCount());
            record.put("acceptedCount", labor.getAcceptedCount());
            record.put("urgent", labor.getUrgent() == 1);
            
            records.add(record);
        }
        
        return records;
    }

    /**
     * 获取状态名称
     */
    private String getStatusName(String status) {
        switch (status) {
            case "recruiting":
                return "招聘中";
            case "closed":
                return "已关闭";
            case "completed":
                return "已完成";
            default:
                return "未知状态";
        }
    }

    /**
     * 格式化日期时间
     */
    private String formatDateTime(java.time.LocalDateTime dateTime) {
        if (dateTime == null) {
            return "";
        }
        return dateTime.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
    }

    /**
     * 获取劳务的应聘者信息
     */
    @GetMapping("/applications/{laborId}")
    public Result<java.util.List<Map<String, Object>>> getLaborApplications(
            @PathVariable Long laborId,
            HttpServletRequest request) {
        try {
            // 从token中获取用户ID
            String token = getTokenFromRequest(request);
            Long userId = jwtUtils.getStudentIdFromToken(token);

            // 验证用户是否有权限查看此劳务的应聘者信息
            Labor labor = laborService.getLaborDetail(laborId);
            if (labor == null || !labor.getPublisherId().equals(userId)) {
                return Result.error("无权限查看此劳务的应聘者信息");
            }

            // 获取应聘者列表
            java.util.List<com.campus.help.vo.LaborApplicationVO> applications = laborService.getLaborApplications(laborId, userId);
            
            // 转换为前端需要的格式
            java.util.List<Map<String, Object>> applicationList = new java.util.ArrayList<>();
            for (com.campus.help.vo.LaborApplicationVO application : applications) {
                Map<String, Object> appInfo = new HashMap<>();
                appInfo.put("id", application.getId());
                appInfo.put("applicantId", application.getApplicantId());
                appInfo.put("applicationTime", formatDateTime(application.getApplicationTime()));
                appInfo.put("status", application.getStatus());
                appInfo.put("statusName", application.getStatusDescription());
                appInfo.put("applicationNote", application.getApplicationNote());
                appInfo.put("reviewTime", formatDateTime(application.getReviewTime()));
                appInfo.put("reviewNote", application.getReviewNote());
                appInfo.put("completeTime", formatDateTime(application.getCompleteTime()));
                appInfo.put("completeNote", application.getCompleteNote());
                
                // 应聘者基本信息（现在直接从VO中获取）
                Map<String, Object> applicantInfo = new HashMap<>();
                applicantInfo.put("id", application.getApplicantId());
                applicantInfo.put("nickname", application.getApplicantNickname());
                applicantInfo.put("avatar", application.getApplicantAvatar());
                applicantInfo.put("phone", application.getApplicantPhone());
                applicantInfo.put("qq", application.getApplicantQq());
                applicantInfo.put("wechat", application.getApplicantWechat());
                appInfo.put("applicantInfo", applicantInfo);
                
                applicationList.add(appInfo);
            }

            return Result.success(applicationList);
        } catch (Exception e) {
            log.error("获取应聘者信息失败", e);
            return Result.error("获取应聘者信息失败: " + e.getMessage());
        }
    }



    /**
     * 取消劳务
     */
    @PostMapping("/cancel/{laborId}")
    public Result<String> cancelLabor(@PathVariable Long laborId, HttpServletRequest request) {
        try {
            // 从token中获取用户ID
            String token = getTokenFromRequest(request);
            Long userId = jwtUtils.getStudentIdFromToken(token);

            // 验证用户是否有权限取消此劳务
            Labor labor = laborService.getLaborDetail(laborId);
            if (labor == null || !labor.getPublisherId().equals(userId)) {
                return Result.error("无权限取消此劳务");
            }

            // 取消劳务
            boolean success = laborService.closeLabor(laborId, userId);
            if (success) {
                return Result.success("劳务已取消");
            } else {
                return Result.error("取消失败");
            }
        } catch (Exception e) {
            log.error("取消劳务失败", e);
            return Result.error("取消劳务失败: " + e.getMessage());
        }
    }

    /**
     * 标记劳务为已完成
     */
    @PostMapping("/complete/{laborId}")
    public Result<String> completeLabor(@PathVariable Long laborId, HttpServletRequest request) {
        try {
            // 从token中获取用户ID
            String token = getTokenFromRequest(request);
            Long userId = jwtUtils.getStudentIdFromToken(token);

            // 验证用户是否有权限完成此劳务
            Labor labor = laborService.getLaborDetail(laborId);
            if (labor == null || !labor.getPublisherId().equals(userId)) {
                return Result.error("无权限完成此劳务");
            }

            // 标记劳务为已完成
            labor.setStatus("completed");
            laborMapper.updateById(labor);

            log.info("劳务标记为已完成: laborId={}, publisherId={}", laborId, userId);
            return Result.success("劳务已标记为完成");
        } catch (Exception e) {
            log.error("完成劳务失败", e);
            return Result.error("完成劳务失败: " + e.getMessage());
        }
    }

    /**
     * 从请求中获取token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        if (authorization != null && authorization.startsWith("Bearer ")) {
            return authorization.substring(7);
        }
        throw new RuntimeException("Token不能为空");
    }
}
